<template>
  <nav class="navbar navbar-dark bg-primary justify-content-between mb-4 px-4">
    <router-link class="navbar-brand" to="/">知也专栏</router-link>
    <ul v-if="isLogin" class="list-inline mb-0">
      <li class="list-inline-item">
        <dropdown :title="`你好 ${user.name}`">
          <dropdown-item
            ><a href="#" class="dropdown-item">新建文章</a></dropdown-item
          >
          <dropdown-item disabled
            ><a href="#" class="dropdown-item">编辑资料</a></dropdown-item
          >
          <dropdown-item
            ><router-link
              to="/login"
              @click="handleLogout"
              class="dropdown-item"
              >退出登录</router-link
            ></dropdown-item
          >
        </dropdown>
      </li>
    </ul>
    <ul v-else class="list-inline mb-0">
      <li class="list-inline-item">
        <router-link to="/login" class="btn btn-outline-light my-2"
          >登录</router-link
        >
      </li>
      <li class="list-inline-item">
        <router-link to="/login" class="btn btn-outline-light my-2"
          >注册</router-link
        >
      </li>
    </ul>
  </nav>
</template>

<script lang="ts">
import { computed, defineComponent, PropType } from "vue";
import Dropdown from "./Dropdown.vue";
import DropdownItem from "./DropdownItem.vue";
import { UserProps, useStore } from "@/store/index";
import { useRouter } from "vue-router";

export default defineComponent({
  props: {
    user: {
      type: Object as PropType<UserProps>,
      required: true,
    },
  },
  setup() {
    const store = useStore();
    const router = useRouter();
    const handleLogout = async () => {
      await store.dispatch("logout");
      router.push({ name: "login" });
    };
    const isLogin = computed(() => store.state.isLogin);

    return {
      isLogin,
      handleLogout,
    };
  },
  components: {
    Dropdown,
    DropdownItem,
  },
});
</script>
